console.log(`background: ${new Date().getTime()}`)
async function sleep( sec=1){
    milisec = sec * 1000;
    return new Promise ( resolve => {
        setTimeout(resolve,milisec);
        console.log(`slept for ${sec} seconds` );

    }
    );

}

function dataInitial() {
    const dataSync = browser.storage.local.get();
    dataSync.then(
        function onGet(item) {
            if (Object.keys(item).length === 0) {
                console.info('no data set let set some default')
                let tmpdata = {
                    "auth": {
                        "user": "admin",
                        "password": "password",
                        "client_id": "EvaluationClientId",
                        "client_secret": "password",
                        "password_type": "query"
                    },
                    "setting": {
                        "ison": true,
                    },

                };
                browser.storage.local.set(tmpdata);
                return tmpdata;

            }
            else {
                // console.info("some data was set")
                for (element in item) {
                    // console.table(element);
                    // console.table(item[element]);
                };
                return item;
            }

        },

        function onError(error) {
            console.table(error);
            return null;

        }

    );

}

window.swaggersettings = 1;
browser.runtime.onInstalled.addListener(dataInitial)
browser.runtime.onMessage.addListener(response);
async function response(message, sender,resp) {
    // response("ok");
    switch (message.iNeed) {
        case "setting":
            await null;
            resp(browser.storage.local.get("setting"));
            //  .then(
            //     item => { response({"setting":item});
                    // console.log("sending these items to contentscript:");
                    // console.log(item);

                    // browser.tabs.sendMessage(
                    //     sender.tab.id,
                    //     {"setting":JSON.stringify(item)}            
                    //                 )
                // });
            break;
        case "isOn":
            await null;
                resp(browser.storage.local.get("setting"));
                // .then(
                //     item => {
                //         let resp = "no"
                //         if (item.setting.ison){resp = "yes";};
                //         response(resp);
                //     }
                //     )
        default:
            break;
    }

}
